package com.adcc.monitoragent.send;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.adcc.monitoragent.send.impl.BroadcastSend;
import com.adcc.monitoragent.util.JsonUtil;
import com.adcc.monitoragent.util.ProtertiesUtil;

/**
 * 消息发送接口
 * @author charlie
 *
 */
public abstract class MessageSend {
	private final static Logger log = LoggerFactory
			.getLogger(MessageSend.class);
	
	private static List<MessageSend> sendList = new ArrayList<MessageSend>();
	/**
	 * 创建连接
	 * @param ip
	 * @param port
	 * @return
	 */
	public abstract boolean connect(String url);
	/**
	 * 发送对象
	 * @param message
	 * @return
	 */
	public abstract boolean send(String message);
	public static String clusterName;
	
	/**
	 * 初始化消息连接
	 */
	public static void init() {
		init(ProtertiesUtil.getClusterName(), ProtertiesUtil.getSendUrls());
	}
	/**
	 * 初始化消息连接
	 */
	public static void init(String clusterName, List<Object> urls) {
		MessageSend.clusterName = clusterName;
		//初始化发送对象
		for (Object url : urls) {
			BroadcastSend send = new BroadcastSend();
			send.connect(url.toString());
			sendList.add(send);
		}
	}
	/**
	 * 客户端调用发送
	 * @param message
	 * @return
	 */
	public static boolean sendMsg(Object message) {
		//json转换
		String json = JsonUtil.beanToJson(message);
		//加入集群名
		json = clusterName + json;
		boolean flag = true;
		for (MessageSend send : sendList) {
			if(!send.send(json)) {
				flag = false;
			}
		}
		if(flag) {
			log.info("广播成功:" + json);
		} else {
			log.warn("部分地址广播失败:" + json);
		}
		return flag;
	}
	
}
